package com.region.http.client.core;

import com.region.common.adapter.logging.LoggerAdapter;
import com.region.common.adapter.logging.LoggerAdapterFactory;
import com.region.core.env.PropertiesOperator;
import com.region.core.env.PropertySourceLocator;
import com.region.core.env.listener.PropertyRefreshListener;
import com.region.http.client.model.RequestMeta;
import com.region.http.client.utils.LockUtils;

import java.util.*;

/**
 * @author 26225
 * @date 2024/7/13 23:25
 * @description
 */
public class RequestMetaPropertiesOperator implements PropertiesOperator {

    private final LoggerAdapter loggerAdapter = LoggerAdapterFactory.getLogger(RequestMetaPropertiesOperator.class);

    private PropertiesOperator delegate;

    private Map<String, List<RequestMeta>> variableBindMeta;

    private ClientProxyHandler handler;

    public RequestMetaPropertiesOperator(PropertiesOperator operator) {
        this.delegate = operator;
    }

    public void setVariableBindMeta(Map<String, List<RequestMeta>> variableBindMeta) {
        this.variableBindMeta = variableBindMeta;
    }

    public void setHandler(ClientProxyHandler handler) {
        this.handler = handler;
    }

    @Override
    public void addPath(String path) {
        delegate.addPath(path);
    }

    @Override
    public void addLocator(PropertySourceLocator locator) {
        delegate.addLocator(locator);
    }

    @Override
    public void addRefreshListener(PropertyRefreshListener listener) {
        delegate.addRefreshListener(listener);
    }

    @Override
    public Object get(String keyName) {
        return delegate.get(keyName);
    }

    @Override
    public Object get(String keyName, Object defaultValue) {
        return delegate.get(keyName, defaultValue);
    }

    @Override
    public void refresh(String keyName, Object newValue) {
        List<RequestMeta> metas = variableBindMeta.get(keyName);
        LockUtils.getWriteLock().lock();
        try {
            delegate.refresh(keyName, newValue);
            for (RequestMeta requestMeta : metas) {
                handler.refreshEnvInfo(requestMeta);
            }
        } catch (Exception e) {
            loggerAdapter.error("The refresh environment error.", e);
        } finally {
            LockUtils.getWriteLock().unlock();
        }
    }

    @Override
    public void load(Map<Object, Object> properties) {
        delegate.load(properties);
    }
}
